package com.hymjweb.demo.framework.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;


public class SerializeUtil {
	/** 
	 * 序列化 
	 * @param <T>
	 * @param object 
	 * @return 
	 */
	public static <T> byte[] serialize(T object) {
		if (object == null) {
			return null;
		}
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		byte[] bytes = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			bytes = baos.toByteArray();
		} catch (Exception e) {
			//Logs.get().error(e);
		} finally {
			close(oos);
			close(baos);
		}
		return bytes;
	}

	/** 
	 * 反序列化 
	 * @param <T>
	 *  
	 * @param bytes 
	 * @return 
	 */
	public static <T> T unserialize(byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			return (T) ois.readObject();
		} catch (Exception e) {
			//Logs.get().error(e);
		} finally {
			close(bais);
			close(ois);
		}
		return null;
	}

	/** 
	 * 序列化 list 集合 
	 * @param <T>
	 *  
	 * @param list 
	 * @return 
	 */
	public static <T> byte[] serializeList(List<T> list) {

		if (list == null || list.size() <= 0) {
			return null;
		}

		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		byte[] bytes = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			for (Object obj : list) {
				oos.writeObject(obj);
			}
			bytes = baos.toByteArray();
		} catch (Exception e) {
			//Logs.get().error(e);
		} finally {
			close(oos);
			close(baos);
		}
		return bytes;
	}

	/** 
	 * 反序列化 list 集合 
	 * @param <T>
	 *  
	 * @param lb 
	 * @return 
	 */
	public static <T> List<T> unserializeList(byte[] bytes) {
		if (bytes == null) {
			return null;
		}

		List<T> list = new ArrayList<T>();
		ByteArrayInputStream bais = null;
		ObjectInputStream ois = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ois = new ObjectInputStream(bais);
			while (bais.available() > 0) {
				T obj = (T) ois.readObject();
				if (obj == null) {
					break;
				}
				list.add(obj);
			}
		} catch (Exception e) {
			//Logs.get().error(e);
		} finally {
			close(bais);
			close(ois);
		}
		return list;
	}

	/** 
	 * 关闭io流对象 
	 *  
	 * @param closeable 
	 */
	public static void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (Exception e) {
				//Logs.get().error(e);
			}
		}
	}
}
